#include <stdio.h>
#include <stdlib.h>
#include "lib/confdata.h"
#include "lib/util.h"

int test1 (void)
{
  int rc = 1;
  run2_env_spec_t * envspec;
  run2_env_t * env;
#if defined (_WIN32) && !defined(__CYGWIN__)
  const char * expected_PATH = "/c/e;/c/d;/c/c;/c/b;/c/a;/c/WINDOWS/system32;/c/f;.";
#else
  const char * expected_PATH = "/c/e:/c/d:/c/c:/c/b:/c/a:/c/WINDOWS/system32:/c/f:.";
#endif
  const char * expected_SHELL = "/c/MinGW/bin/sh.exe";
  const char * expected_ACCUM = "edcba_MIDDLE_uvxyz";

  const char * result_PATH = NULL;
  const char * result_SHELL = NULL;
  const char * result_ACCUM = NULL;

  env = run2_env_create ();
  envspec = run2_env_get_var (env, "PATH");
  run2_env_spec_set (envspec, "/c/WINDOWS/system32");
  run2_env_spec_prepend (envspec, "/c/a");
  run2_env_spec_prepend (envspec, "/c/b");
  run2_env_spec_prepend (envspec, "/c/c");
  run2_env_spec_prepend (envspec, "/c/d");
  run2_env_spec_prepend (envspec, "/c/e");
  run2_env_spec_append (envspec, "/c/f");
  envspec = run2_env_get_var (env, "SHELL");
  run2_env_spec_set (envspec, "/c/MinGW/bin/sh.exe");
  envspec = run2_env_get_var (env, "PATH");
  run2_env_spec_append  (envspec, ".");
  envspec = run2_env_get_var (env, "ACCUM");
  run2_env_spec_set (envspec, "MIDDLE");
  run2_env_spec_prepend (envspec, "a_");
  run2_env_spec_prepend (envspec, "b");
  run2_env_spec_prepend (envspec, "c");
  run2_env_spec_prepend (envspec, "d");
  run2_env_spec_prepend (envspec, "e");
  run2_env_spec_append (envspec, "_u");
  run2_env_spec_append (envspec, "v");
  run2_env_spec_append (envspec, "x");
  run2_env_spec_append (envspec, "y");
  run2_env_spec_append (envspec, "z");
  run2_env_print  (stdout, 0, "test1", env);

  run2_apply_env (env);
  rc = 0;

  result_PATH = getenv ("PATH");
  result_SHELL = getenv ("SHELL");
  result_ACCUM = getenv ("ACCUM");
  rc = 0;

  if (strcmp(result_PATH, expected_PATH) != 0)
    {
      errorMsg ("FAILED test 1a:\n\texpected: PATH=%s\n\tresult  : PATH=%s",
                expected_PATH, result_PATH);
      rc++;
    }
  if (strcmp(result_SHELL, expected_SHELL) != 0)
    {
      errorMsg ("FAILED test 1b:\n\texpected: SHELL=%s\n\tresult  : SHELL=%s",
                expected_SHELL, result_SHELL);
      rc++;
    }
  if (strcmp(result_ACCUM, expected_ACCUM) != 0)
    {
      errorMsg ("FAILED test 1c:\n\texpected: ACCUM=%s\n\tresult  : ACCUM=%s",
                expected_ACCUM, result_ACCUM);
      rc++;
    }

cleanup:
  run2_env_delete (env);
  return rc;
}

int main (int argc, char * argv[])
{
  int rc = 0;
  run2_set_program_name (argv[0]);
  run2_set_verbose_level (RUN2_DEFAULT_LOG_LEVEL);
  rc += test1 ();
  return rc;
}

